<template>
	<cl-page>
		<view class="combo-promotion-page">
			<!-- 自定义导航栏 -->
			<cl-topbar title="套餐促销" background-color="#ff6b6b">
				<template #append>
					<view class="rules-btn" @tap="showRules">
						<cl-icon name="cl-icon-question" color="#fff" :size="40" />
					</view>
				</template>
			</cl-topbar>

			<!-- 横幅区域 -->
			<view class="banner-section">
				<image
					src="/static/images/combo-banner.jpg"
					mode="aspectFill"
					class="banner-image"
				/>
				<view class="banner-overlay">
					<view class="banner-content">
						<view class="banner-title">超值套餐组合</view>
						<view class="banner-subtitle">多买多省，健康实惠</view>
					</view>
				</view>
			</view>

			<!-- 筛选标签 -->
			<view class="filter-tags">
				<scroll-view scroll-x class="tag-scroll">
					<view class="tag-list">
						<view
							class="tag-item"
							:class="{ active: currentTag === tag.value }"
							v-for="tag in tagOptions"
							:key="tag.value"
							@tap="selectTag(tag.value)"
						>
							<cl-icon v-if="tag.icon" :name="tag.icon" :size="32" />
							<text>{{ tag.label }}</text>
						</view>
					</view>
				</scroll-view>
			</view>

			<!-- 套餐列表 -->
			<view class="combo-list">
				<view
					class="combo-card"
					v-for="combo in comboList"
					:key="combo.id"
					@tap="toComboDetail(combo.id)"
				>
					<!-- 套餐头部 -->
					<view class="combo-header">
						<view class="combo-title">
							<cl-icon name="cl-icon-present" :size="36" color="#ff6b6b" />
							<text>{{ combo.name }}</text>
						</view>
						<view class="combo-badge" v-if="combo.hot">
							<cl-icon name="cl-icon-hot" :size="24" />
							<text>热卖</text>
						</view>
					</view>

					<!-- 商品列表 -->
					<view class="combo-products">
						<view
							class="product-item"
							v-for="(product, index) in combo.products"
							:key="index"
						>
							<view class="product-image">
								<image
									:src="product.imgUrl || '/static/icon/no-image.png'"
									mode="aspectFill"
								/>
								<view class="product-quantity">x{{ product.quantity }}</view>
							</view>
							<view class="product-info">
								<view class="product-name">{{ product.name }}</view>
								<view class="product-spec">{{ product.spec }}</view>
								<view class="product-price">
									<text class="original">¥{{ product.originalPrice }}</text>
								</view>
							</view>
						</view>
					</view>

					<!-- 价格信息 -->
					<view class="combo-price">
						<view class="price-left">
							<view class="total-label">套餐价</view>
							<view class="save-info">
								共省 <text class="save-amount">¥{{ combo.savedAmount }}</text>
							</view>
						</view>
						<view class="price-right">
							<view class="original-total">¥{{ combo.originalTotal }}</view>
							<view class="combo-total">
								<text class="symbol">¥</text>
								<text class="value">{{ combo.comboPrice }}</text>
							</view>
						</view>
					</view>

					<!-- 操作按钮 -->
					<view class="combo-actions">
						<view class="stock-status" :class="{ 'low-stock': combo.stock < 10 }">
							<cl-icon name="cl-icon-box" :size="28" />
							<text>库存: {{ combo.stock }}套</text>
						</view>
						<cl-button
							type="primary"
							size="medium"
							round
							@tap.stop="addToCart(combo)"
							:disabled="combo.stock <= 0"
						>
							<cl-icon name="cl-icon-cart" />
							<text>加入购物车</text>
						</cl-button>
					</view>

					<!-- 促销标签 -->
					<view class="promo-tags" v-if="combo.tags && combo.tags.length > 0">
						<view class="promo-tag" v-for="(tag, idx) in combo.tags" :key="idx">
							{{ tag }}
						</view>
					</view>
				</view>
			</view>

			<!-- 空状态 -->
			<cl-empty v-if="isEmpty" description="暂无套餐促销" image="/static/icon/empty-box.png">
				<cl-button type="primary" size="small" round @tap="toHome">去首页看看</cl-button>
			</cl-empty>

			<!-- 加载更多 -->
			<cl-loadmore
				v-if="!isEmpty"
				:loading="loading"
				:finished="finished"
				@loadmore="loadMore"
			/>

			<!-- 规则说明弹窗 -->
			<cl-popup v-model="showRulesPopup" direction="center" :size="600">
				<view class="rules-popup">
					<view class="popup-header">
						<text class="title">套餐促销规则</text>
						<cl-icon name="cl-icon-close" :size="40" @tap="showRulesPopup = false" />
					</view>
					<view class="popup-content">
						<view class="rule-item">
							<view class="rule-title">1. 套餐优惠</view>
							<view class="rule-content">
								套餐内商品按照套餐价销售，相比单独购买更加优惠。
							</view>
						</view>
						<view class="rule-item">
							<view class="rule-title">2. 不可拆分</view>
							<view class="rule-content"> 套餐商品不可拆分购买，需整套购买。 </view>
						</view>
						<view class="rule-item">
							<view class="rule-title">3. 库存限制</view>
							<view class="rule-content"> 套餐库存有限，售完即止。 </view>
						</view>
						<view class="rule-item">
							<view class="rule-title">4. 其他优惠</view>
							<view class="rule-content"> 套餐商品不再享受其他优惠活动。 </view>
						</view>
					</view>
				</view>
			</cl-popup>
		</view>
	</cl-page>
</template>

<script lang="ts" setup>
import { ref, computed } from "vue";
import { onReady, onReachBottom } from "@dcloudio/uni-app";
import { useCool, usePager } from "/@/cool";
import { useShoppingCart } from "/@/hooks/shopping-cart";

const { service, router } = useCool();
const { onRefresh, onData, isEmpty, loading, finished } = usePager();
const { addGoods } = useShoppingCart();

// 标签选项
const tagOptions = [
	{ label: "全部", value: "", icon: "" },
	{ label: "家庭常备", value: "family", icon: "cl-icon-home" },
	{ label: "慢病管理", value: "chronic", icon: "cl-icon-yao" },
	{ label: "营养保健", value: "nutrition", icon: "cl-icon-vitamin" },
	{ label: "母婴专区", value: "baby", icon: "cl-icon-baby" },
	{ label: "季节养生", value: "season", icon: "cl-icon-leaf" },
];

// 当前选中的标签
const currentTag = ref("");

// 套餐列表
const comboList = ref<any[]>([]);

// 显示规则弹窗
const showRulesPopup = ref(false);

// 获取套餐列表
function refresh(params?: any) {
	const { data, next } = onRefresh(params);

	onData((list) => {
		// 处理真实API数据
		const processedList = list.map((promo: any) => {
			const details = promo.details || [];
			const products = details.map((detail: any) => ({
				name: detail.goodsInfo?.oracleGoodsName || detail.goodsInfo?.title || "商品名称",
				spec: detail.goodsInfo?.goodsSpec || "规格",
				imgUrl: detail.goodsInfo?.mainPic || "/static/icon/no-image.png",
				quantity: detail.num || 1,
				originalPrice: detail.goodsInfo?.price?.toFixed(2) || "0.00",
			}));

			// 计算价格
			const originalTotal = details.reduce((sum: number, detail: any) => {
				return sum + (detail.goodsInfo?.price || 0) * (detail.num || 0);
			}, 0);

			const comboTotal = details.reduce((sum: number, detail: any) => {
				return sum + (detail.taxprice || 0) * (detail.num || 0);
			}, 0);

			return {
				id: promo.billNo,
				billNo: promo.billNo,
				name: promo.promName || "套餐促销",
				hot: Math.random() > 0.7, // 随机热门标识
				products,
				originalTotal: originalTotal.toFixed(2),
				comboPrice: comboTotal.toFixed(2),
				savedAmount: (originalTotal - comboTotal).toFixed(2),
				stock: 99, // 默认库存
				tags: promo.status === 1 ? ["进行中"] : ["已结束"],
				startTime: promo.startTime,
				endTime: promo.endTime,
				status: promo.status,
			};
		});

		if (data.page == 1) {
			comboList.value = processedList;
		} else {
			comboList.value.push(...processedList);
		}
	});

	// 调用真实API
	return next(
		service.goods.promo.getByPromType({
			promType: "TC", // 套餐促销类型
			...params,
		})
	);
}

// 选择标签
function selectTag(value: string) {
	currentTag.value = value;
	refresh({ page: 1, tag: value });
}

// 显示规则
function showRules() {
	showRulesPopup.value = true;
}

// 跳转套餐详情
function toComboDetail(billNo: string) {
	// 可以跳转到促销详情页面或商品详情页面
	router.push({
		path: "/pages/market/promotion-detail",
		query: { billNo, type: "TC" },
	});
}

// 加入购物车
async function addToCart(combo: any) {
	try {
		// 确认购买套餐
		uni.showModal({
			title: "确认购买",
			content: `确认购买套餐"${combo.name}"，价格¥${combo.comboPrice}？`,
			success: async (res) => {
				if (res.confirm) {
					try {
						// 调用创建套餐订单API
						const response = await service.goods.promo_order.createComboOrder({
							billNo: combo.billNo,
							remark: "移动端套餐购买",
						});

						uni.showToast({
							title: "订单创建成功",
							icon: "success",
						});
						// 跳转到订单列表
						setTimeout(() => {
							router.push("/pages/order/list");
						}, 1500);
					} catch (error) {
						console.error("创建套餐订单失败:", error);
						uni.showToast({
							title: "订单创建失败",
							icon: "none",
						});
					}
				}
			},
		});
	} catch (error) {
		console.error("加入购物车失败:", error);
	}
}

// 跳转首页
function toHome() {
	router.push("/pages/index/home");
}

// 加载更多
function loadMore() {
	refresh({ page: comboList.value.length / 10 + 1 });
}

onReady(() => {
	refresh();
});

onReachBottom(() => {
	if (!loading.value && !finished.value) {
		loadMore();
	}
});
</script>

<style lang="scss" scoped>
.combo-promotion-page {
	min-height: 100vh;
	background-color: #f5f5f5;
}

// 横幅区域
.banner-section {
	position: relative;
	height: 320rpx;
	overflow: hidden;

	.banner-image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.banner-overlay {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: linear-gradient(180deg, rgba(0, 0, 0, 0.2) 0%, rgba(0, 0, 0, 0.6) 100%);
		display: flex;
		align-items: flex-end;
		padding: 40rpx;
	}

	.banner-content {
		color: #fff;

		.banner-title {
			font-size: 40rpx;
			font-weight: 600;
			margin-bottom: 12rpx;
		}

		.banner-subtitle {
			font-size: 28rpx;
			opacity: 0.9;
		}
	}
}

// 规则按钮
.rules-btn {
	padding: 10rpx;
}

// 筛选标签
.filter-tags {
	background-color: #fff;
	padding: 20rpx 0;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

	.tag-scroll {
		white-space: nowrap;
	}

	.tag-list {
		display: inline-flex;
		padding: 0 20rpx;
		gap: 20rpx;
	}

	.tag-item {
		display: inline-flex;
		align-items: center;
		gap: 8rpx;
		padding: 16rpx 32rpx;
		background-color: #f8f8f8;
		border-radius: 36rpx;
		font-size: 28rpx;
		color: #666;
		transition: all 0.3s;

		&.active {
			background: linear-gradient(135deg, #ff6b6b, #ff5252);
			color: #fff;
			box-shadow: 0 4rpx 12rpx rgba(255, 107, 107, 0.3);
		}

		&:active {
			transform: scale(0.95);
		}
	}
}

// 套餐列表
.combo-list {
	padding: 0 20rpx 20rpx;
}

.combo-card {
	background-color: #fff;
	border-radius: 20rpx;
	padding: 32rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	position: relative;
	overflow: hidden;
	transition: all 0.3s;

	&:active {
		transform: scale(0.98);
	}

	// 套餐头部
	.combo-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24rpx;

		.combo-title {
			display: flex;
			align-items: center;
			gap: 12rpx;
			font-size: 32rpx;
			font-weight: 600;
			color: #333;
		}

		.combo-badge {
			display: flex;
			align-items: center;
			gap: 4rpx;
			padding: 8rpx 20rpx;
			background: linear-gradient(135deg, #ff9800, #ff5722);
			color: #fff;
			border-radius: 30rpx;
			font-size: 24rpx;
			font-weight: 600;
			box-shadow: 0 4rpx 8rpx rgba(255, 87, 34, 0.3);
		}
	}

	// 商品列表
	.combo-products {
		border-top: 2rpx solid #f5f5f5;
		border-bottom: 2rpx solid #f5f5f5;
		padding: 24rpx 0;
		margin-bottom: 24rpx;

		.product-item {
			display: flex;
			align-items: center;
			gap: 20rpx;
			margin-bottom: 20rpx;

			&:last-child {
				margin-bottom: 0;
			}

			.product-image {
				position: relative;
				width: 120rpx;
				height: 120rpx;
				border-radius: 12rpx;
				overflow: hidden;
				background-color: #f8f9fa;

				image {
					width: 100%;
					height: 100%;
					object-fit: cover;
				}

				.product-quantity {
					position: absolute;
					bottom: 0;
					right: 0;
					background-color: rgba(0, 0, 0, 0.6);
					color: #fff;
					padding: 4rpx 12rpx;
					border-radius: 12rpx 0 12rpx 0;
					font-size: 22rpx;
				}
			}

			.product-info {
				flex: 1;

				.product-name {
					font-size: 28rpx;
					color: #333;
					font-weight: 500;
					margin-bottom: 8rpx;
				}

				.product-spec {
					font-size: 24rpx;
					color: #999;
					margin-bottom: 8rpx;
				}

				.product-price {
					.original {
						font-size: 24rpx;
						color: #999;
						text-decoration: line-through;
					}
				}
			}
		}
	}

	// 价格信息
	.combo-price {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24rpx;

		.price-left {
			.total-label {
				font-size: 26rpx;
				color: #666;
				margin-bottom: 8rpx;
			}

			.save-info {
				font-size: 24rpx;
				color: #ff6b6b;

				.save-amount {
					font-weight: 600;
					font-size: 28rpx;
				}
			}
		}

		.price-right {
			text-align: right;

			.original-total {
				font-size: 26rpx;
				color: #999;
				text-decoration: line-through;
				margin-bottom: 8rpx;
			}

			.combo-total {
				display: flex;
				align-items: baseline;
				color: #ff4444;

				.symbol {
					font-size: 28rpx;
					font-weight: 600;
				}

				.value {
					font-size: 48rpx;
					font-weight: 700;
					margin-left: 4rpx;
				}
			}
		}
	}

	// 操作按钮
	.combo-actions {
		display: flex;
		justify-content: space-between;
		align-items: center;

		.stock-status {
			display: flex;
			align-items: center;
			gap: 8rpx;
			font-size: 26rpx;
			color: #666;

			&.low-stock {
				color: #ff6b6b;
			}
		}
	}

	// 促销标签
	.promo-tags {
		position: absolute;
		top: 20rpx;
		right: -80rpx;
		transform: rotate(45deg);
		display: flex;
		flex-direction: column;
		gap: 8rpx;

		.promo-tag {
			background: linear-gradient(135deg, #ff6b6b, #ff5252);
			color: #fff;
			padding: 8rpx 120rpx;
			font-size: 22rpx;
			text-align: center;
			box-shadow: 0 4rpx 8rpx rgba(255, 107, 107, 0.3);
		}
	}
}

// 规则弹窗
.rules-popup {
	background-color: #fff;
	border-radius: 24rpx;
	overflow: hidden;

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 32rpx;
		border-bottom: 2rpx solid #f0f0f0;

		.title {
			font-size: 32rpx;
			font-weight: 600;
			color: #333;
		}
	}

	.popup-content {
		padding: 32rpx;

		.rule-item {
			margin-bottom: 32rpx;

			&:last-child {
				margin-bottom: 0;
			}

			.rule-title {
				font-size: 28rpx;
				font-weight: 600;
				color: #333;
				margin-bottom: 12rpx;
			}

			.rule-content {
				font-size: 26rpx;
				color: #666;
				line-height: 1.6;
			}
		}
	}
}
</style>
